package com.example.demo;

import java.util.concurrent.CompletableFuture;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String index() {
        return "Hello World";
    }

    @Autowired
    private AsyncTasks asyncTasks;

    @RequestMapping("/hello_async")
    public String indexAsync() throws Exception {
        asyncTasks.doTaskOne();
        asyncTasks.doTaskTwo();
        asyncTasks.doTaskThree();
        return "Hello World";
    }

    @RequestMapping("/hello_async_callback")
    public String indexAsyncCallback() throws Exception {
        long start = System.currentTimeMillis();

        CompletableFuture<String> task1 = asyncTasks.doTaskOne();
        CompletableFuture<String> task2 = asyncTasks.doTaskTwo();
        CompletableFuture<String> task3 = asyncTasks.doTaskThree();
        task1.thenAccept((result) -> {
            System.out.println("TASK COMPLETE: " + result);
        });
        task2.thenAccept((result) -> {
            System.out.println("TASK COMPLETE: " + result);
        });
        task3.thenAccept((result) -> {
            System.out.println("TASK COMPLETE: " + result);
        });
        CompletableFuture.allOf(task1, task2, task3).join();

        long end = System.currentTimeMillis();

        System.out.println("任务全部完成，总耗时：" + (end - start) + "毫秒");
        return "Hello World";
    }

}